using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Repositories;

namespace Lzfy_Refund_Service.Services
{
    /// <summary>
    /// UUM用户服务实现
    /// </summary>
    public class UumUserService : IUumUserService
    {
        private readonly IUumUserRepository _uumUserRepository;
        private readonly ILogger<UumUserService> _logger;

        public UumUserService(
            IUumUserRepository uumUserRepository,
            ILogger<UumUserService> logger)
        {
            _uumUserRepository = uumUserRepository;
            _logger = logger;
        }

        /// <summary>
        /// 根据用户名查询UUM用户信息
        /// </summary>
        public async Task<UumUserQueryResponse> GetUserByUserNameAsync(string userName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName))
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "用户名不能为空"
                    };
                }

                var user = await _uumUserRepository.GetUserByUserNameAsync(userName);
                
                if (user == null)
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "未找到指定用户名的用户信息"
                    };
                }

                return new UumUserQueryResponse
                {
                    Success = true,
                    Message = "查询成功",
                    Data = user
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据用户名查询UUM用户信息失败: UserName={UserName}", userName);
                return new UumUserQueryResponse
                {
                    Success = false,
                    Message = "查询用户信息时发生错误"
                };
            }
        }

        /// <summary>
        /// 根据用户ID查询UUM用户信息
        /// </summary>
        public async Task<UumUserQueryResponse> GetUserByIdAsync(int userId)
        {
            try
            {
                if (userId <= 0)
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "用户ID必须大于0"
                    };
                }

                var user = await _uumUserRepository.GetUserByIdAsync(userId);
                
                if (user == null)
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "未找到指定ID的用户信息"
                    };
                }

                return new UumUserQueryResponse
                {
                    Success = true,
                    Message = "查询成功",
                    Data = user
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据用户ID查询UUM用户信息失败: UserId={UserId}", userId);
                return new UumUserQueryResponse
                {
                    Success = false,
                    Message = "查询用户信息时发生错误"
                };
            }
        }

        /// <summary>
        /// 根据工号查询UUM用户信息
        /// </summary>
        public async Task<UumUserQueryResponse> GetUserByPeopleIdentifierAsync(string peopleIdentifier)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(peopleIdentifier))
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "工号不能为空"
                    };
                }

                var user = await _uumUserRepository.GetUserByPeopleIdentifierAsync(peopleIdentifier);
                
                if (user == null)
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "未找到指定工号的用户信息"
                    };
                }

                return new UumUserQueryResponse
                {
                    Success = true,
                    Message = "查询成功",
                    Data = user
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据工号查询UUM用户信息失败: PeopleIdentifier={PeopleIdentifier}", peopleIdentifier);
                return new UumUserQueryResponse
                {
                    Success = false,
                    Message = "查询用户信息时发生错误"
                };
            }
        }

        /// <summary>
        /// 检查用户名是否存在
        /// </summary>
        public async Task<bool> UserNameExistsAsync(string userName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName))
                {
                    return false;
                }

                return await _uumUserRepository.UserNameExistsAsync(userName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查用户名是否存在失败: UserName={UserName}", userName);
                return false;
            }
        }

        /// <summary>
        /// 更新用户信息（仅更新task_amount、usertype、partybranch、userphone字段）
        /// </summary>
        public async Task<UumUserUpdateResponse> UpdateUserAsync(UumUserUpdateRequest request)
        {
            try
            {
                if (request == null)
                {
                    return new UumUserUpdateResponse
                    {
                        Success = false,
                        Message = "请求参数不能为空"
                    };
                }

                if (request.Id <= 0)
                {
                    return new UumUserUpdateResponse
                    {
                        Success = false,
                        Message = "用户ID无效"
                    };
                }

                var result = await _uumUserRepository.UpdateUserAsync(request);
                
                if (result)
                {
                    _logger.LogInformation("更新用户信息成功: UserId={UserId}", request.Id);
                    return new UumUserUpdateResponse
                    {
                        Success = true,
                        Message = "更新成功"
                    };
                }
                else
                {
                    return new UumUserUpdateResponse
                    {
                        Success = false,
                        Message = "未找到指定用户或更新失败"
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新用户信息失败: UserId={UserId}", request?.Id);
                return new UumUserUpdateResponse
                {
                    Success = false,
                    Message = "更新用户信息时发生错误"
                };
            }
        }

        /// <summary>
        /// 搜索用户信息
        /// </summary>
        public async Task<UumUserSearchResponse> SearchUsersAsync(UumUserSearchRequest request)
        {
            try
            {
                if (request == null)
                {
                    return new UumUserSearchResponse
                    {
                        Success = false,
                        Message = "请求参数不能为空",
                        Items = new List<UumUserSearchItem>()
                    };
                }

                var items = await _uumUserRepository.SearchUsersAsync(request);
                var itemList = items.ToList();
                
                _logger.LogInformation("搜索用户信息成功，共找到 {Count} 条记录", itemList.Count);
                
                return new UumUserSearchResponse
                {
                    Success = true,
                    Message = "搜索成功",
                    Items = itemList
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索用户信息失败");
                return new UumUserSearchResponse
                {
                    Success = false,
                    Message = "搜索用户信息时发生错误",
                    Items = new List<UumUserSearchItem>()
                };
            }
        }
    }
}